package presale_house.handler;


import presale_house.service.ClientService;
import presale_house.service.HouseService;
import presale_house.service.impl.ClientServiceImpl;
import presale_house.service.impl.HouseServiceImpl;
import presale_house.show.HouseList.HouseView;
import presale_house.show.MainView;
import presale_house.show.view.AddClientView;
import presale_house.show.view.AddHouseView;
import presale_house.show.view.UpdateClientView;
import presale_house.show.view.UpdateHouseView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class HouseViewHandler implements ActionListener{
    private HouseView houseView;
    public HouseViewHandler(HouseView houseView){
        this.houseView=houseView;
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton=(JButton) e.getSource();
        String Text=jButton.getText();
        if(Text.equals("添加")){
       new AddHouseView(houseView);
        } else if (Text.equals("删除")) {
            int[]selectedHouseIds= houseView.getSelectedHouseIds();
            if(selectedHouseIds.length==0){
                JOptionPane.showMessageDialog(houseView,"请选择要删除的行");
                return;
            }
            int option =JOptionPane.showConfirmDialog(houseView,"确认要删除选择的这"+selectedHouseIds.length+"行吗?",
                    "确认删除",JOptionPane.YES_NO_OPTION);
            if(option==JOptionPane.YES_OPTION){//确认删除
                HouseService houseService =new HouseServiceImpl();
                boolean deleteResult= houseService.delete(selectedHouseIds);
                if(deleteResult){
                    //更新表格数据
                    houseView.reloadTable();
                    JOptionPane.showMessageDialog(houseView,"删除成功");
                }else{
                    JOptionPane.showMessageDialog(houseView,"删除失败");
                }
            }

        } else if (Text.equals("修改")) {
            int[]selectedHouseIds= houseView.getSelectedHouseIds();
            if(selectedHouseIds.length!=1){
                JOptionPane.showMessageDialog(houseView,"一次只能修改一行");
                return;
            }
    new UpdateHouseView(houseView,selectedHouseIds[0]);
        } else if (Text.equals("搜索")) {
            houseView.setPageNow(1);
            houseView.reloadTable();
        } else if (Text.equals("上一页")) {
            houseView.setPageNow(houseView.getPageNow()-1);
            System.out.println(houseView.getPageNow());
            houseView.reloadTable();
        } else if (Text.equals("下一页")) {
            houseView.setPageNow(houseView.getPageNow()+1);
            System.out.println(houseView.getPageNow());
            houseView.reloadTable();
        } else if (Text.equals("返回主菜单")) {
            new MainView();
            houseView.dispose();
        }
    }
}
